package com.hxd.otc;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.NotificationCompat;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.listener.OnHighlightDrewListener;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.app.hubert.guide.model.HighlightOptions;
import com.baidu.mobstat.StatService;
import com.flyco.animation.BaseAnimatorSet;
import com.hxd.otc.base.BaseApplication;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.TakeOrderStatusEnum;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.dialog.SingBlocksDialog;
import com.hxd.otc.dialog.SystemNoticeDialog;
import com.hxd.otc.dialog.TakeOrderStatusMenuPopupWindow;
import com.hxd.otc.event.Event;
import com.hxd.otc.main.bean.TabBottomBean;
import com.hxd.otc.module.fiat_deal.fragment.DealFragment;
import com.hxd.otc.module.home.fragment.HomePageFragment;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.module.my.bean.AppInfoBean;
import com.hxd.otc.module.my.bean.NoticeBean;
import com.hxd.otc.module.my.fragment.MyFragment;
import com.hxd.otc.module.order.bean.RedPointBean;
import com.hxd.otc.module.order.fragment.OrderFragment;
import com.hxd.otc.mvp.contract.MainContract;
import com.hxd.otc.mvp.home.MainPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.NotificationHelper;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.utils.download.DownloadManagerUtil;
import com.hxd.otc.widget.DragFloatActionButton;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class MainActivity extends PermissionActivity<MainPresenter> implements MainContract.IMainView, TabHost.OnTabChangeListener, View.OnTouchListener {

    @BindView(android.R.id.tabhost)
    FragmentTabHost mTabHost;
    @BindView(R.id.dragFloatActionButton)
    DragFloatActionButton mDragFloatActionButton;
    @BindView(R.id.tv_single_status)
    TextView mTvSingleStatus;
    @BindView(R.id.iv_single_status_bg)
    ImageView mIvSingleStatusBg;

    private boolean isFirst = true;
    private AppInfoBean mUpdateVersionInfo;
    private MultipleBlocksDialog mOpenNotificationDialog;
    private SystemNoticeDialog systemNoticeDialog;
    private SingBlocksDialog singBlocksDialog;

    public static final String EXTRA_SKIP_FROM_FLAG = "skipFromFlag";//用于SingleTask复用MainActvity的表示
    public static final int EXTRA_SKIP_FROM_FLAG_OTHER = 0;
    private TakeOrderStatusMenuPopupWindow mTakeOrderStatusMenuPopupWindow;
    Disposable mDisposable;

    private ObjectAnimator mScaleX;
    private ObjectAnimator mScaleY;
    private AnimatorSet mScaleAnim;
    private boolean isStop;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }

    @Override
    protected void initPermissions() {
        requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                MainActivity.super.initPermissions();
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {

            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
            }

            @Override
            public void onLowVersion() {
                MainActivity.super.initPermissions();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    @Override
    protected void initView() {
        // 开发时调用，建议上线前关闭，以免影响性能
        StatService.setDebugOn(BuildConfig.isDebug);
        initFragmentTabHost();
    }

    private void initFragmentTabHost() {
        List<TabBottomBean> bottomTabsData = mPresenter.getBottomTabsData();
        Class[] fragments = new Class[]{HomePageFragment.class, DealFragment.class, OrderFragment.class, MyFragment.class};

        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
        for (int i = 0; i < bottomTabsData.size(); i++) {
            TabBottomBean tabBottomBean = bottomTabsData.get(i);
            View indicatorView = View.inflate(this, R.layout.tab_main_indicator, null);
            TextView tvTitle = indicatorView.findViewById(R.id.tv_tab);
            tvTitle.setText(tabBottomBean.getTabName());
            tvTitle.setCompoundDrawablesWithIntrinsicBounds(null, ResourceUtil.getDrawable(tabBottomBean.getTabRes()), null, null);
            Bundle bundle = new Bundle();
            mTabHost.addTab(mTabHost.newTabSpec(tabBottomBean.getTabName()).setIndicator(indicatorView), fragments[i], bundle);
        }
        mTabHost.getTabWidget().getChildAt(2).setOnTouchListener(this);
        mTabHost.setOnTabChangedListener(this);
        mTabHost.setCurrentTab(0);

    }


    @Override
    protected void initData() {
        if (isFirst) {
            registerEventBus();
            isFirst = false;
        }

        if (mUpdateVersionInfo == null) {
            mPresenter.getUpdateVersionInfo();
        }
        openNotification();

        queryTakeOrderStatus();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getNosenseMessageNotice();
        if (mTakeOrderStatusMenuPopupWindow != null && mTakeOrderStatusMenuPopupWindow.isShowing()) {
            return;
        }
        if (mDragFloatActionButton != null) {
            updateTakeOrderStatusUI(mPresenter.getTakeOrderStatusEnum());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopScaleAnim();
    }

    private void getNosenseMessageNotice() {
        if ((UserHelper.isLogin() && UserHelper.isNonInductivePaySilver()) || (UserHelper.isLogin() && UserHelper.isSilver())) {
            if (mDisposable != null && !mDisposable.isDisposed()) {
                return;
            }
            mDisposable = Flowable.interval(0, 60, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                        @SuppressLint("DefaultLocale")
                        @Override
                        public void accept(Long aLong) throws Exception {
                            mPresenter.getNosenseMessageNotice();
                        }
                    })
                    .subscribe();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getExtras() != null && intent.getExtras().containsKey("isSkipToDealPage")
                && intent.getExtras().getBoolean("isSkipToDealPage")) {
            mTabHost.setCurrentTab(1);
            return;
        }
        queryTakeOrderStatus();
        getNosenseMessageNotice();
    }

    /**
     * 查询无感支付广告商的接单状态
     */
    private void queryTakeOrderStatus() {
        if (UserHelper.isLogin() && UserHelper.isNonInductivePaySilver()) {
            mPresenter.queryTakeOrderStatus();
            stopScaleAnim();
        } else {
            updateTakeOrderStatusUI(null);
        }
    }

    public void getAfficheList() {
        mPresenter.getAfficheList(1, 5);
    }


    private void openNotification() {
        if (!CommonUtil.isNotificationEnabled()) {
            mOpenNotificationDialog = new MultipleBlocksDialog(this);
            mOpenNotificationDialog.setTitle(getString(R.string.allow_notification))
                    .setContent(getString(R.string.notification_ba_is_closed))
                    .setTvSure(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mOpenNotificationDialog.dismiss();
                            CommonUtil.skipAppDetailActivity();
                        }
                    })
                    .show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event.TokenMissEvent missEvent) {
        if (missEvent.getMsg() == 0) {
            UserHelper.logout(this);
        }
    }

    /**
     * 当订单状态改变时，重新请求数据
     *
     * @param refreshMainRedEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(Event.RefreshMainRedEvent refreshMainRedEvent) {
        mTabHost.getTabWidget().getChildAt(2).
                findViewById(R.id.tv_red).setVisibility(refreshMainRedEvent.getNum() > 0 ? View.VISIBLE : View.GONE);

    }

    @Override
    public void getPointFlag(RedPointBean bean) {
        mTabHost.getTabWidget().getChildAt(2).
                findViewById(R.id.tv_red).setVisibility(bean.noPayDetailCount > 0 || bean.payDetailCount > 0 ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void initEvent() {
        mDragFloatActionButton.setOnTouchDragListener(new DragFloatActionButton.OnDragListener() {
            @Override
            public void onTouchDown() {
                stopScaleAnim();
            }

            @Override
            public void onDragUp() {
                startScaleAnim();
            }
        });
    }

    @Override
    public void getUpdateVersionInfoSuccess(AppInfoBean appInfoBean) {
        mUpdateVersionInfo = appInfoBean;
        doNewVersionUpdate();
    }

    private void doNewVersionUpdate() {
        if (DownloadManagerUtil.hasNewVersion(mUpdateVersionInfo, false)) {
            DownloadManagerUtil.showUpdateVersionDialog(this, mUpdateVersionInfo);
        }
    }

    @Override
    public void getAfficheListSuccess(ArrayList<NoticeBean> noticeBeans) {
        if (UserHelper.isLogin() && !noticeBeans.get(0).isLook()) {
            systemNoticeDialog = new SystemNoticeDialog(this);
            systemNoticeDialog.setNoticeBean(noticeBeans.get(0));
            systemNoticeDialog.show();
        }
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < noticeBeans.size(); i++) {
            arrayList.add(noticeBeans.get(i).getTitle());
        }

        HomePageFragment homePageFragment = (HomePageFragment) getSupportFragmentManager().findFragmentByTag(
                mPresenter.getBottomTabsData().get(0).getTabName());
        if (homePageFragment != null && arrayList.size() > 0) {
            homePageFragment.setTitleList(arrayList);
        }
    }

    @OnClick(R.id.dragFloatActionButton)
    public void onClick(View view) {
        showMenu();
    }

    public void showMenu() {
        if (mTakeOrderStatusMenuPopupWindow == null) {
            mTakeOrderStatusMenuPopupWindow = new TakeOrderStatusMenuPopupWindow(this);
            mTakeOrderStatusMenuPopupWindow
                    .setOnSelectListener(new TakeOrderStatusMenuPopupWindow.OnSelectListener() {
                        @Override
                        public void onSelected(TakeOrderStatusEnum takeOrderStatusEnum) {
                            showSpinnerDlg(getString(R.string.in_the_switch), false);
                            mPresenter.updateTakeOrderStatus(takeOrderStatusEnum);
                        }
                    })
                    .setWidth(mDragFloatActionButton.getWidth())
            ;
        }
        mTakeOrderStatusMenuPopupWindow.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                updateTakeOrderStatusSuccess(mPresenter.getTakeOrderStatusEnum());
            }
        });
        mTakeOrderStatusMenuPopupWindow.offset(0, 0)
                .setTakeOrderStatusEnum(TakeOrderStatusEnum.StopOrders.equals(mPresenter.getTakeOrderStatusEnum()) ? TakeOrderStatusEnum.InTheOrder : TakeOrderStatusEnum.StopOrders)
                .showAnim(getTakeOrderStatusMenuShowAnim(mDragFloatActionButton.isTop()))
                .dismissAnim(getTakeOrderStatusMenuDismissAnim(mDragFloatActionButton.isTop()))
                .gravity(mDragFloatActionButton.isTop() ? Gravity.BOTTOM : Gravity.TOP)
                .anchorView(mDragFloatActionButton)
                .show();
    }

    @NonNull
    private BaseAnimatorSet getTakeOrderStatusMenuDismissAnim(final boolean isTop) {
        return new BaseAnimatorSet() {

            @Override
            public void setAnimation(View view) {
                int dp64 = DataUtils.dp2px(getApplication(), 64);
                duration = 300;
                animatorSet.playTogether(ObjectAnimator.ofFloat(view, "alpha", 1, -1f),//
                        ObjectAnimator.ofFloat(view, "translationY", 0, isTop ? -dp64 : dp64));
            }
        };
    }

    @NonNull
    private BaseAnimatorSet getTakeOrderStatusMenuShowAnim(final boolean isTop) {
        return new BaseAnimatorSet() {

            @Override
            public void setAnimation(View view) {
                int dp64 = DataUtils.dp2px(getApplication(), 64);
                duration = 300;
                animatorSet.playTogether(ObjectAnimator.ofFloat(view, "alpha", -0.5f, 1),//
                        ObjectAnimator.ofFloat(view, "translationY", isTop ? -dp64 : dp64, 0));
            }
        };
    }

    /**
     * 更新接单按钮UI
     *
     * @param takeOrderStatusEnum null：不显示接单按钮，TakeOrderStatusEnum.InTheOrder：接单中，TakeOrderStatusEnum.StopOrders:暂停接单
     */
    private void updateTakeOrderStatusUI(TakeOrderStatusEnum takeOrderStatusEnum) {
        if (takeOrderStatusEnum == null) {
            stopScaleAnim();
            mDragFloatActionButton.setVisibility(View.GONE);
        } else {
            boolean isTakeOrder = TakeOrderStatusEnum.InTheOrder.equals(takeOrderStatusEnum);
            mIvSingleStatusBg.setImageResource(isTakeOrder ? R.drawable.shape_hovering_take_orders_bg : 0);
            mTvSingleStatus.setBackgroundResource(isTakeOrder ?
                    R.drawable.shape_hovering_take_orders : R.drawable.shape_hovering_stop_orders);
            mTvSingleStatus.setText(isTakeOrder ? R.string.in_the_order : R.string.stop_orders_lin_feed);
            mDragFloatActionButton.setVisibility(View.VISIBLE);
            if (isTakeOrder) {
                startScaleAnim();
            } else {
                stopScaleAnim();
            }
            showGuide();
        }
    }

    private void startScaleAnim() {
        if (mScaleAnim == null) {
            createScaleAnim();
        } else {
            mScaleAnim.setDuration(800);
            mScaleX.setRepeatCount(ValueAnimator.INFINITE);
            mScaleY.setRepeatCount(ValueAnimator.INFINITE);
        }
        isStop = false;
        mScaleAnim.start();
    }

    private void stopScaleAnim() {
        if (mScaleAnim != null) mScaleAnim.setDuration(8);
        isStop = true;
    }

    private void createScaleAnim() {
        mScaleX = ObjectAnimator.ofFloat(mIvSingleStatusBg, "scaleX", 1f, 1.178f);
        mScaleY = ObjectAnimator.ofFloat(mIvSingleStatusBg, "scaleY", 1f, 1.178f);
        mScaleX.setRepeatMode(ValueAnimator.REVERSE);
        mScaleX.setRepeatCount(ValueAnimator.INFINITE);
        mScaleX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (isStop) {
                    animation.setRepeatCount(1);
                }
            }
        });
        mScaleY.setRepeatMode(ValueAnimator.REVERSE);
        mScaleY.setRepeatCount(ValueAnimator.INFINITE);
        mScaleY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (isStop) {
                    animation.setRepeatCount(1);
                }
            }
        });
        mScaleAnim = new AnimatorSet();
        mScaleAnim.setInterpolator(new LinearInterpolator());
        mScaleAnim.playTogether(mScaleX, mScaleY);
        mScaleAnim.setDuration(800);
    }

    public void showGuide() {
        HighlightOptions options = new HighlightOptions.Builder()
                .setOnHighlightDrewListener(new OnHighlightDrewListener() {
                    @Override
                    public void onHighlightDrew(Canvas canvas, RectF rectF) {
                        Paint paint = new Paint();
                        paint.setColor(Color.WHITE);
                        paint.setStyle(Paint.Style.STROKE);
                        paint.setStrokeWidth(DataUtils.dp2px(MainActivity.this, 2));
                        paint.setAntiAlias(true);
                        canvas.drawCircle(rectF.centerX(), rectF.centerY(), rectF.width() / 2, paint);
                    }
                })
                .build();
        NewbieGuide.with(this)
                .setLabel("guide_of_take_order_status")
                .alwaysShow(false)
                .addGuidePage(
                        GuidePage.newInstance()
                                .addHighLightWithOptions(mTvSingleStatus, HighLight.Shape.CIRCLE, options)
                                .setEverywhereCancelable(true)//是否点击任意位置消失引导页，默认true
                                .setLayoutRes(R.layout.view_guide_take_orders)
                                .setBackgroundColor(getResources().getColor(R.color.color_D6000000))//设置背景色，建议使用有透明度的颜色
                )
                .show();
    }

    @Override
    public void queryTakeOrderSuccess(TakeOrderStatusEnum takeOrderStatusEnum) {
        updateTakeOrderStatusUI(takeOrderStatusEnum);
    }

    @Override
    public void queryTakeOrderFail(String errMessage) {
        updateTakeOrderStatusUI(null);
    }

    @Override
    public void updateTakeOrderStatusSuccess(TakeOrderStatusEnum takeOrderStatusEnum) {
        dismissSpinnerDlg();
        updateTakeOrderStatusUI(takeOrderStatusEnum);
        UIUtils.dismissDialog(mTakeOrderStatusMenuPopupWindow);
    }

    @Override
    public void updateTakeOrderStatusFail(String errMessage) {
        dismissSpinnerDlg();
        showToast(errMessage);
        UIUtils.dismissDialog(mTakeOrderStatusMenuPopupWindow);
    }

    @Override
    public void setNosenseMessageNotice(int numbers) {
        if (numbers > 0) {
            if (!CommonUtil.isBackground(this)) {
                SingBlocksDialog singBlocksDialog = new SingBlocksDialog(BaseApplication.getInstance().getTopActivity())
                        .setContent(getString(R.string.you_have_new_message), 17)
                        .setTitleGone();
                if (singBlocksDialog.isShowing()) {
                    singBlocksDialog.dismiss();
                }
                singBlocksDialog.show();
            } else {
                NotificationCompat.Builder builder = NotificationHelper.createDefaultBuilder();

                builder.setSmallIcon(R.mipmap.logo);
                builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.logo));
                builder.setAutoCancel(true);
                builder.setContentText(getString(R.string.you_have_new_message));
                builder.setContentTitle("WOTC");
                builder.setDefaults(Notification.DEFAULT_SOUND);
                builder.setWhen(System.currentTimeMillis());
                Intent intent = new Intent(this, MainActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
                builder.setContentIntent(pendingIntent);

                NotificationHelper.getDefaultNotificationManager().notify(10, builder.build());
            }

        }
    }

    @Override
    public void clearNosenseRefresh() {//当TOKEN 失效的时候， 应该清楚 实时刷新 请求
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }

    @Override
    public void onTabChanged(String tabId) {
        if (UserHelper.isLogin() && UserHelper.isNonInductivePaySilver() && mPresenter.getTakeOrderStatusEnum() == null) {
            queryTakeOrderStatus();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mScaleAnim != null) {
            mScaleAnim.end();
            mScaleAnim = null;
        }
        UIUtils.dismissDialog(mTakeOrderStatusMenuPopupWindow);
        UIUtils.dismissDialog(mOpenNotificationDialog);
        UIUtils.dismissDialog(systemNoticeDialog);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!UserHelper.isLogin()) {
            $startActivity(LoginActivity.class);
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        super.onStateNotSaved();
        super.onBackPressed();
    }
}
